loadStorePacksMod = {}

local modDir = g_currentModDirectory
local modName = g_currentModName

function loadStorePacksMod.loadMapData(self, superFunc, xmlFile, missionInfo, baseDirectory)
    superFunc(self, xmlFile, missionInfo, baseDirectory)

    -- Загрузка store packs из modDesc.xml
    local xmlFile = XMLFile.load("ModFile", modDir .. "modDesc.xml")

    local packsXMLKey = "modDesc.storePacks.storePack"
    if xmlFile:hasProperty(packsXMLKey) then
        for _, key in xmlFile:iterator(packsXMLKey) do
            local name = xmlFile:getString(key .. "#name")
            local title = xmlFile:getString(key .. "#title")
            local imageFilename = xmlFile:getString(key .. "#image")

            -- Проверка корректности данных
            if not name or name == "" then
                print(string.format("Ошибка: Некорректное имя store pack в %s", key))
            elseif not title or title == "" then
                print(string.format("Ошибка: Некорректное название store pack в %s", key))
            elseif not imageFilename or imageFilename == "" then
                print(string.format("Ошибка: Некорректное изображение store pack в %s", key))
            else
                -- Если title содержит ссылку на локализованный текст, извлекаем его
                if title:sub(1, 6) == "$l10n_" then
                    title = g_i18n:getText(title:sub(7))
                end

                -- Добавляем pack в менеджер
                self:addPack(name, title, imageFilename, modDir)

                -- Добавляем store items в pack
                xmlFile:iterate(key .. ".storeItem", function(_, storeItemKey)
                    local xmlFilename = xmlFile:getString(storeItemKey)
                    if xmlFilename and xmlFilename ~= "" then
                        local fullPath = Utils.getFilename(xmlFilename, baseDirectory)
                        if fileExists(fullPath) then
                            self:addPackItem(name, fullPath)
                        else
                            print(string.format("Ошибка: StoreItem '%s' не найден для store pack '%s'", xmlFilename, name))
                        end
                    else
                        print(string.format("Ошибка: Пустой путь для storeItem в %s", storeItemKey))
                    end
                end)
            end
        end
    else
        print("Предупреждение: StorePacks не найдены в modDesc.xml.")
    end

    xmlFile:delete()

    return true
end

StoreManager.loadMapData = Utils.overwrittenFunction(StoreManager.loadMapData, loadStorePacksMod.loadMapData)
